import BaseCanvas from "./BaseCanvas";
import Base2DPainter from "../Painter/Base2DPainter";
import AnimationFrameRequest from "../../utils/AnimationFrameRequest";

export default class BaseAnimationCanvas extends BaseCanvas {
    /**
     * @param id {string}
     * @param zIndex {number=}
     * @param painterType {Base2DPainter}
     */
    constructor({id, zIndex = 0, painterType = Base2DPainter}) {
        super({id, zIndex, painterType});
        // init animation request
        this.isRunning = false;
    }

    /**
     *
     * @param painting {BaseAnimationPainting}
     */
    addPainting(painting) {
        super.addPainting(painting);
        if (this.isRunning) {
            painting.beDrawn.call(painting, painting.painter);
        }
    }

    drawAll() {
        super.drawAll();
    }

    startDrawing() {
        this.isRunning = true;
        this.frameId = AnimationFrameRequest.register(this.drawFrame, this);
    }

    drawFrame() {
        this.clearCanvas();
        this.paintings.forEach((painting) => {
            painting.nextFrame.call(painting, painting.painter);
            painting.nextEffectsFrame.call(painting, painting.painter);
        });
        this.globalCtx.drawImage(this.drawnCanvas, 0, 0);
        if (!this.isRunning) {
            AnimationFrameRequest.cancellation(this.frameId);
        }
    }
}
